<!--登陆-->
<template>
  <view class="page-content login-page-wrapper">
    <!-- 标题 -->
    <view class="login-welcome-wrapper">
      <view class="welcome-prefix">您好，</view>
      <!-- 精策云 -->
      <view class="welcome-suffix">欢迎使用{{ appTitle() }}</view>
    </view>
    <!-- 表单 -->
    <view class="login-form-wrapper">
      <!-- 账户登录 -->
      <template v-if="currentLoginType == 1">
        <view class="input-wrapper" :class="{ 'focusing': currentFocus == 'account' }">
          <view class="input-label">
            用户名
          </view>
          <view class="input-control">
            <u-input :border="false" height="110" v-model="formData.account" placeholder="请输入您的账号" placeholder-style="color: #abb1a9" :custom-style="{ fontSize: '30rpx' }" @focus="handleFocus('account')" @blur="handleFocus('')"/>
          </view>
        </view>
        <view class="input-wrapper" :class="{ 'focusing': currentFocus == 'password' }">
          <view class="input-label">
            密码
          </view>
          <view class="input-control">
            <u-input :border="false" type="password" height="110" v-model="formData.password" placeholder="请输入您的密码" placeholder-style="color: #abb1a9" :custom-style="{ fontSize: '30rpx' }" @focus="handleFocus('password')" @blur="handleFocus('')"/>
          </view>
        </view>
      </template>
      <!-- 短信登录 -->
      <template v-if="currentLoginType == 2">
        <view class="input-wrapper" :class="{ 'focusing': currentFocus == 'account' }">
          <view class="input-label">
            手机号
          </view>
          <view class="input-control">
            <u-input :border="false" type="tel" height="110" v-model="formData.mobile" placeholder="请输入手机号" placeholder-style="color: #abb1a9" :custom-style="{ fontSize: '30rpx' }" @focus="handleFocus('account')" @blur="handleFocus('')"/>
          </view>
        </view>
        <view class="input-wrapper" :class="{ 'focusing': currentFocus == 'password' }">
          <view class="input-label">
            验证码
          </view>
          <view class="input-control with-mobile-code">
            <u-input :border="false" height="110" v-model="formData.code" placeholder="请输入验证码" placeholder-style="color: #abb1a9" :custom-style="{ fontSize: '30rpx' }" @focus="handleFocus('password')" @blur="handleFocus('')"/>
            <view class="verify-control" @click="handleGraphVerifyVisible">{{ buttonText }}</view>
            <u-verification-code :seconds="seconds" ref="uCodeRef" @change="handleVerificodeCompChange"></u-verification-code>
          </view>
        </view>
        
      </template>
      
      <!-- 注册账户和找回密码 -->
      <view class="register-wrapper">
        <view class="left">
          <view @tap.stop="handleRegisterIn">
            <u-icon name="zhuce" custom-prefix="custom-icon" size="32" class="mr-1"></u-icon>
            注册账号        
          </view>
        </view>
        <view class="right">
          <view @tap.stop="handleForgetPassword">
            <u-icon name="mima" custom-prefix="custom-icon" size="32" class="mr-1"></u-icon>
            忘记密码
          </view>
        </view>
      </view>
      <!-- 登录按钮和方式切换 -->
      <view class="access-button-container">
        <view class="access-button-wrapper">
          <view class="access-button login" :class="{ 'disabled': loginButtonDisabled == true }" @tap.stop="handleLogin">
            登录
          </view>
          <view class="devider"></view>
          <view class="access-button switch" @click="handleChangeLoginType()">
            {{ currentLoginType == 1 ? '切换到短信登录' : '切换到密码登录' }}
          </view>
        </view>
      </view>
    </view>
    <!-- 底部隐私政策等 -->
    <view class="privacy-content-wrapper">
      <u-checkbox size="28" class="privacy-checker" v-model="formData.privacyChecked" shape="circle" active-color="#0052d9">
      	我已阅读
      	<text class="privacy-link " @click.stop="hanglgUserManualFn">用户手册</text>
      	及
      	<text class="privacy-link" @click.stop="hanglgPrivacyPolicyFn">隐私政策</text>
        并理解相关条款内容
      </u-checkbox>
    </view>
    
    <verify
    	@success="handleGraphVerifySuccess"
    	ref="VerifyRef"
    	:mode="'pop'"
    	:captchaType="'blockPuzzle'"
    	:imgSize="{ width: '300px', height: '155px' }"
    ></verify>
  </view>
</template>

<script>
import { isValidPhoneNumber } from '@/utils/tool.js';
import { sendVerifyMobileSms, smsCodeLogin, getByUserId, accountPwdLogin, getLoginAfterStatus } from '@/api/apis.js';
import { encrypt } from '@/utils/encrypFile';
import verify from '@/userPages/components/verify/verify.vue';

export default {
	components: {
		verify
	},
	data() {
		return {
      currentFocus: '', //当前输入的控件
      currentLoginType: 1, //1账户2手机号
      formData: {
        account: '',
        password: '',
        
        mobile: '',
        code: '',
        
        privacyChecked: false,
      },
      seconds: 60, //倒计时
      buttonText: '', //验证码按钮文字
		};
	},
  computed: {
    loginButtonDisabled() {
      if (this.currentLoginType == 1) {
        if (!this.formData.account || !this.formData.password) {
          return true;
        }
        return false;
      } else {
        if ((!this.formData.mobile || !this.formData.code) || isValidPhoneNumber(this.formData.mobile) == false) {
          return true;
        }
        return false;
      }
    }
  },
  onLoad() {
	},
	methods: {
		/**
     * @description 登录
     */
    handleLogin() {
      const _that = this;
      let query, api;
      if (this.currentLoginType == 1) {
        if (!this.formData.account || !this.formData.password) {
          this.$u.toast('账号或密码不能为空');
          return;
        } else {
          query = { encryptAccountAndPasswordStr: encrypt(`${this.$u.trim(this.formData.account)}-${this.$u.trim(this.formData.password)}`) };
          api = accountPwdLogin;
        }
      } else {
        if ((!this.formData.mobile || !this.formData.code) || isValidPhoneNumber(this.formData.mobile) == false) {
          this.$u.toast('手机号或验证码错误');
          return;
        } else {
          query = { encryptAccountAndPasswordStr: encrypt(`${this.$u.trim(this.formData.mobile)}-${this.$u.trim(this.formData.code)}`) };
          api = smsCodeLogin
        }
      }
      //隐私政策
      if (this.formData.privacyChecked == false) {
        uni.showModal({
          title: '温馨提示',
          content: '登录即代表您已阅读并理解用户手册及隐私政策所提及的相关信息',
          success: (res) => {
            if (res.confirm == true) {
              this.formData.privacyChecked = true;
              execLogin();
            }
          }
        })
        return;
      }
      execLogin();
      
      //登录函数
      function execLogin() {
        api(query).then(res => {
        	if (res.code == 10000) {
        		uni.setStorage({
        			key: 'ims-token',
        			data: res.data.token
        		});
        		_that.afterLogin(res.data.userId);
        	} else {
        		_that.$u.toast(res.msg);
        	}
        });
      }
    },
    
    /**
     * @description 登录后续
     */
    async afterLogin(userId) {
      let infoRes = await getByUserId({ userId: userId });
      if (infoRes.code == 10000) {
        uni.setStorage({
          key: 'userInfo',
          data: infoRes.data
        });
        let aftRes = await getLoginAfterStatus();
        if (aftRes.code == 10000) {
          this.$Router.replaceAll({
            path: '/pages/home/index'
          });
        } else {
          this.$u.toast(aftRes.msg);
        }
      } else {
        this.$u.toast(infoRes.msg);
      }
    },
    
		/**
     * @description 注册账号
     */
		hanglgSignInFn() {
			this.$Router.push({
				path: '/userPages/pages/register/index'
			});
		},
    
    /**
     * @description 聚焦事件
     * @param {Object} name
     */
    handleFocus(name) {
      this.currentFocus = name;
    },
    
    /**
     * @description 切换登录类型
     */
    handleChangeLoginType() {
      if (this.currentLoginType == 1) {
        this.currentLoginType = 2;
      } else {
        this.currentLoginType = 1;
      }
    },
    
    /**
     * @description 用户手册
     */
    hanglgUserManualFn() {
    	console.log('点击了用户手册');
    },
    
    /**
     * @description 隐私政策
     */
    hanglgPrivacyPolicyFn() {
    	console.log('点击了隐私政策');
    },
    
    /**
     * @description 注册账号
     */
    handleRegisterIn() {
    	this.$Router.push({
    		path: '/userPages/pages/register/index'
    	});
    },
    
    /**
     * @description 忘记密码
     */
    handleForgetPassword() {
    	this.$Router.push({
    		path: '/userPages/pages/forgotPassword/index'
    	});
    },
    
    /**
     * @description 显示图形验证码
     */
    handleGraphVerifyVisible() {
      if (!this.$refs.uCodeRef.canGetCode) return;
      if (!isValidPhoneNumber(this.formData.mobile)) {
        this.$u.toast('请输入正确手机号码');
        return false;
      }
      this.$refs.VerifyRef.show();
    },
    
    /**
     * @description 本地验证通过
     */
    handleGraphVerifySuccess() {
      	this.getCode();
      	this.$refs.VerifyRef.close();
    },
    
    /**
     * @description 验证码组件的值变化事件
     */
    handleVerificodeCompChange(value) {
      this.buttonText = value;
    },
    
    //获取验证码
    getCode() {
    	if (this.$refs.uCodeRef.canGetCode) {
        uni.showLoading({
        	title: '正在获取验证码',
        	mask: true
        });
        sendVerifyMobileSms({ mobile: this.formData.mobile }).then(res => {
    			if (res.code == 10000) {
    				setTimeout(() => {
    					uni.hideLoading();
    					this.$u.toast('验证码已发送');
    					this.$refs.uCodeRef.start();
    				}, 2000);
    			} else {
    				this.$u.toast(res.msg);
    			}
    		});
    	} else {
    		this.$u.toast('验证码已发送，请稍后再试');
    	}
    },
	}
};
</script>

<style lang="scss" scoped>
.login-page-wrapper {
  height: 100vh;
  width: 100vw;
  background: url($custom-bg-img-url + 'login-bg.jpg') no-repeat center -100rpx;
  background-size: cover;
  position: relative;
  
  .login-welcome-wrapper {
    height: calc(420rpx + env(safe-area-inset-top));
    padding: calc(220rpx + env(safe-area-inset-top)) 48rpx 0 48rpx;
    color: #000;
    .welcome-prefix {
      line-height: 1;
      font-size: 42rpx;
      margin-bottom: 8rpx;
    }
    .welcome-suffix {
      line-height: 1;
      font-size: 42rpx;
    }
  }
  
  .login-form-wrapper {
    border: 2px solid #FFFFFF;
    border-bottom: none;
    border-radius: 24rpx 24rpx 0 0;
    height: calc(100vh - (420rpx + env(safe-area-inset-top)));
    background-color: rgba(245, 245, 245, 0.6);
    backdrop-filter: blur(4px);
    padding: 48rpx 48rpx 0 48rpx;
    
    .input-wrapper {
      position: relative;
      margin-bottom: 30rpx;
      .input-label {
        line-height: 1;
        font-size: 32rpx;
      }
      .input-control {
        &.with-mobile-code {
          position: relative;
          .verify-control {
            position: absolute;
            z-index: 1;
            top: 20rpx;
            right: 0;
            height: 80rpx;
            width: 200rpx;
            border-radius: 8rpx;
            color: #FFF;
            background-color: rgba(0, 82, 217, 1);
            display: inline-flex;
            align-items: center;
            justify-content: center;
          }
        }
      }
      border-bottom: 1px solid #EAEAEA;
      &:after {
        content: '';
        position: absolute;
        z-index: 1;
        bottom: 0;
        width: 0px;
        height: 1px;
        background-color: #0052d9;
        transition: all ease .2s;
      }
      &.focusing {
        &:after {
          width: 100%;
        }
      }
    }
  }
  
  //注册 + 找回密码
  .register-wrapper {
    padding-top: 16rpx;
    display: flex;
    align-items: center;
    .left, .right {
      flex: 1;
      display: flex;
      align-items: center;
      view {
        line-height: 1;
        display: inline-flex;
        align-items: center;
        font-size: 26rpx;
        color: #0052d9;
      }
    }
    .left {
      justify-content: flex-start;
    }
    .right {
      justify-content: flex-end;
    }
  }
  
  //按钮区域
  .access-button-container {
    height: calc(100vh - (420rpx + env(safe-area-inset-top)) - 100rpx - 2px - 24rpx - ( (32rpx + 110rpx + 1px + 30rpx) * 2 ) - 36rpx - 16rpx);
    display: flex;
    align-items: center;
    .access-button-wrapper {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        .access-button {
          height: 80rpx;
          width: 100%;
          border-radius: 40rpx;
          background-color: rgba(0, 82, 217, 1);
          display: flex;
          align-items: center;
          justify-content: center;
          color: #FFF;
          font-size: 32rpx;
          &.disabled {
            // background-color: #BBB;
          }
          &.login {}
          &.switch {
            color: rgba(0, 82, 217, 1);
            background-color: rgba(0, 82, 217, 0.1);
          }
        }
        
        .devider {
          margin: 24rpx 0;
          width: 300rpx;
          height: 1px;
          background-color: rgba(0, 82, 217, 0.1);
        }
      }
  }
  
  
  .privacy-content-wrapper {
    position: absolute;
    bottom: env(safe-area-inset-bottom);
    left: 0;
    right: 0;
    height: 100rpx;
    width: 100vw;
    display: flex;
    align-items: center;
    justify-content: center;
    
    ::v-deep .privacy-checker {
      .u-checkbox__label {
        color: #d2d2d2;
        font-size: 26rpx;
      }
    }
    .privacy-link {
      color: #888;
    }
  }
}
</style>
